package com.gxa.meiye.portal.shop.shopLogin.controller;

import com.gxa.meiye.core.common.JsonResult;
import com.gxa.meiye.core.common.ResponseData;
import com.gxa.meiye.core.utils.RestUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @Author cc
 * @PackageName meiye
 * @Package com.gxa.portal.shop.shopLogin.controller
 * @Date 2022/7/22 14:44
 * @Version 1.0
 */
@RestController
@RequestMapping("shop")
@Api(tags = "登录接口")
@Slf4j
public class PortalLoginController {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    public static final String TOKEN = "shopLoginToken:";
    @PostMapping("loginButton")
    @ApiOperation("门店登录")
    public ResponseData login(String email, String pwd) {
        ResponseData rd = new ResponseData();
        String url = "http://1.117.60.194:8080/shop/shopLogin";
        MultiValueMap<String,Object> params = new LinkedMultiValueMap<>();
        params.add("email",email);
        params.add("pwd",pwd);
        Map map = RestUtils.postWithParams(url, params);
        Object data = map.get("data");
        if(StringUtils.isEmpty(data)){
            rd.setCode(500);
            rd.setMsg("邮箱或密码错误");
        }else{
            String token = UUID.randomUUID().toString().replace("-","");
            ValueOperations<String, Object> logToken = redisTemplate.opsForValue();
            logToken.set(TOKEN,token,2, TimeUnit.HOURS);
            rd.setData(data);
            rd.setCode(200);
            rd.setMsg("登录成功");
            rd.setToken(token);
        }
        return rd;
    }
    @PostMapping("checkWithToken")
    @ApiOperation("查询token")
    public Map checkWithToken(String token) {
        JsonResult jsonResult = new JsonResult();
        if(token.equals(redisTemplate.opsForValue().get(TOKEN))){
            //更新时间
            redisTemplate.opsForValue().set(TOKEN,token,2,TimeUnit.HOURS);
            jsonResult.setCode("200");
            jsonResult.setMsg("token正确");
        }else {
            jsonResult.setCode("201");
            jsonResult.setMsg("token不正确");
        }
        return jsonResult.getMap();
    }

}